package com.zzy.furns.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author 韩顺平
 * @version 1.0
 * 基于druid数据库连接池的工具类
 */
public class JDBCUtilsByDruid {

    private static DataSource ds;
    private static ThreadLocal<Connection> transactionThreadLocal = new ThreadLocal<>();
    //在静态代码块完成 ds初始化
    static {
        Properties properties = new Properties();
        try {
            /**
             * 1.直接按照 properties.load(new FileInputStream("src\\druid.properties")); 方式加载配置文件会报错：
             *   java.io.FileNotFoundException: src\druid.properties (系统找不到指定的路径。)
             * 2.原因是在JavaWeb下，运行时真正读取文件是在 out/artifacts/Ajax_war_exploded/WEB-INF/classes 目录下
             * 3.所以需要使用类加载器完成配置文件的加载
             */
            properties.load(JDBCUtilsByDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //编写getConnection方法
    public static Connection getConnection() throws SQLException {
        Connection connection = transactionThreadLocal.get();
        if (connection == null){
            //还没有从数据库连接池中拿取连接 则从数据库连接池中拿取连接并放入到ThreadLocal中
            connection = ds.getConnection();
            transactionThreadLocal.set(connection);
        }

        //关闭事务自动提交
        connection.setAutoCommit(false);

        //已经从数据库连接池中拿取连接并保存在ThreadLocal中 直接取出返回即可
        return transactionThreadLocal.get();
    }

    public static void commitTransaction(){
        Connection connection = transactionThreadLocal.get();
        if (connection != null){
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    //将数据库连接放回数据库连接池
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        //清除该线程的该ThreadLocal对象，保证放回线程池的线程是无污染的
        transactionThreadLocal.remove();
    }

    public static void rollback(){
        Connection connection = transactionThreadLocal.get();
        if (connection != null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        transactionThreadLocal.remove();
    }

    //关闭连接, 老师再次强调： 在数据库连接池技术中，close 不是真的断掉连接
    //而是把使用的Connection对象放回连接池
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {

        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
